package com.fast.alden.security.component;

import com.fast.alden.common.entity.dto.ResponseResult;
import com.fast.alden.common.exception.BizException;
import com.fast.alden.common.exception.BizExceptionEnum;
import com.fast.alden.common.util.JsonUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 未授权处理器
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        // 此Handler中的异常不会交给ExceptionHandlerAdvice处理，因此需要手动设置响应
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        BizException exception = new BizException(e, BizExceptionEnum.USER_DOSE_NOT_LOGGED_IN);
        writer.println(JsonUtils.toJSON(ResponseResult.fail(HttpServletResponse.SC_UNAUTHORIZED, exception.getCode(), exception.getLocalizedMessage())));
        writer.flush();
        writer.close();
    }
}
